// DriveNotes. Copyright (c) 2011, Andrei Senchuk. All rights reserved.
package net.taviscaron.drivenotes.server.model.dao.impl;

import java.util.List;
import net.taviscaron.drivenotes.server.model.dao.UserDAO;
import net.taviscaron.drivenotes.shared.model.entity.User;
import net.taviscaron.drivenotes.server.util.EncryptionUtil;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * UserDAOImpl implementation
 * @author Andrei Senchuk
 */
public class UserDAOImpl extends HibernateDaoSupport implements UserDAO {

    public User findById(Long id) {
        return getHibernateTemplate().load(User.class, id);
    }

    public User findByCredentials(String username, String password) {
        List list = getHibernateTemplate().find("from User where username = ?", username);
        if(list.size() > 0) {
            User user = (User) list.get(0);
            if(user != null && EncryptionUtil.calculateHash(password, user.getSalt()).equals(user.getPassword())) {
                return user;
            }
        }
        return null;
    }

    public void save(User user) {
        getHibernateTemplate().saveOrUpdate(user);
    }

    public void remove(User obj) {
        getHibernateTemplate().delete(obj);
    }

    public User findByUsername(String username) {
        List list = getHibernateTemplate().find("from User where username = ?", username);
        if(list.size() > 0) {
            return (User)list.get(0);
        }
        return null;
    }
}
